<template>
  <div>
    <div style="margin-bottom: 2%;"></div>
    <el-card style="margin:0 auto;width: 96%;">
      <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="16%">
        <el-form-item  label="课程安排名称" prop="teachName">
          <el-input style="width: 50%;" v-model="ruleForm.teachName" placeholder="请输入课程安排名称"></el-input>
        </el-form-item>
        <el-form-item label="选择课程" prop="courseId">
          <el-select  v-model="ruleForm.courseId"
                      style="width: 30%;"
                      clearable filterable
                      placeholder="请选择课程">
            <el-option v-for="item in course" :key="item.courseId"
                       :label="item.courseId +' - '+ item.courseName"
                       :value="item.courseId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择教师" prop="teacherId">
          <el-select  v-model="ruleForm.academyId"
                      style="width: 20%;margin-right: 2%"
                      clearable filterable
                      placeholder="请先选择教师所属的学院"
                      @change="teacherInit(ruleForm.academyId,'')">
            <el-option v-for="item in academy" :key="item.academyId"
                       :label="item.academyId +' - '+ item.academyName"
                       :value="item.academyId">
            </el-option>
          </el-select>
          <el-select  v-model="ruleForm.teacherId"
                      style="width: 28%;"
                      clearable filterable
                      placeholder="请选择教师">
            <el-option v-for="item in teacher" :key="item.teacherId"
                       :label="item.teacherId +' - '+ item.teacherName"
                       :value="item.teacherId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择学期" prop="termId">
          <el-select  v-model="ruleForm.termId"
                      style="width: 25%;"
                      filterable
                      placeholder="请选择学期">
            <el-option v-for="item in terms" :key="item.termId"
                       :label="item.termName" :value="item.termId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="选择考核方式" prop="method">
          <el-select v-model="ruleForm.method" style="width: 25%">
            <el-option label="考试" :value="'考试'"/>
            <el-option label="考察" :value="'考察'"/>
            <el-option label="其它" :value="'其它'"/>
          </el-select>
        </el-form-item>
        <el-form-item label="及格分 : "><!--及格分/满分-->
          <el-input style="width: 20%;margin-right: 2%"
                    placeholder="请输入及格线成绩"
                    v-model="ruleForm.passingScore"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> 满分 : </span>
          <el-input style="width: 20%;"
                    placeholder="请输入满分成绩"
                    v-model="ruleForm.fullScore"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
        </el-form-item>
        <el-form-item label="平时成绩 : ">
          <el-input style="width: 8%;margin-right: 1%"
                    v-model="ruleForm.usualPct"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> 实践成绩 : </span>
          <el-input style="width: 8%;margin-right: 1%"
                    v-model="ruleForm.expPct"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> 期中成绩 : </span>
          <el-input style="width: 8%;margin-right: 1%"
                    v-model="ruleForm.midPct"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> 期末成绩 : </span>
          <el-input style="width: 8%;margin-right: 1%"
                    v-model="ruleForm.finalPct"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> 其它成绩 : </span>
          <el-input style="width: 8%;margin-right: 1%"
                    v-model="ruleForm.otherPct"
                    oninput ="value=value.replace(/[^0-9]/g,'')">
          </el-input>
          <span> (占最终成绩百分比 %)</span>
        </el-form-item>
        <el-form-item label="添加班级/个人 :">
          <el-row class="tac">
            <el-col :span="10">
              <el-input style="width: 48%;margin-right: 2%" v-model="clazzId"
                        placeholder="请输入待查找的班级"></el-input>
              <el-button @click="findClazz()" type="primary">立即查找</el-button>
              <el-checkbox-group v-model="ruleForm.clazz" style="margin-top: 2%">
                <el-checkbox-button v-for="item in clazzList"
                                    :label="item.clazzId"
                                    :key="item.clazzId">{{item.clazzId + '班'}}
                </el-checkbox-button><!--此处:label才是值,{{xx}}xx是显示的文本..-->
              </el-checkbox-group>
            </el-col>
            <el-col :span="13">
              <el-input style="width: 48%;margin-right: 2%" v-model="studentId"
                        placeholder="请输入待查找的学号"></el-input>
              <el-button @click="findStudent()" type="primary">立即查找</el-button>
              <el-checkbox-group v-model="ruleForm.student" style="margin-top: 2%">
                <el-checkbox-button v-for="item in studentList"
                                    :label="item.stuId"
                                    :key="item.stuId">{{item.stuId + ' ' + item.stuName}}
                </el-checkbox-button><!--此处:label才是值,{{xx}}xx是显示的文本..-->
              </el-checkbox-group>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即提交</el-button>
          <el-button style="margin-left:5%" @click="returnPage()">返回</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  data(){
    return{
      form:{
        teachId: '',
      },
      academy:[],
      teacher:[],
      course:[],
      terms:[],
      clazzId:'',
      clazzList:[],
      studentId:'',
      studentList:[],
      ruleForm:{
        teachId: -1,
        teachName:'',
        courseId:'',
        teacherId:'',
        termId: '',
        method:'考试',
        clazz:[],
        student:[],
        fullScore: 100,     //满分 - 默认100
        passingScore: 60,   //及格分 - 默认60
        usualPct: 0,        //平时成绩 - 默认0
        expPct: 0,          //实践成绩 - 默认0
        midPct: 0,          //期中成绩 - 默认0
        finalPct: 100,      //期末成绩 - 默认100
        otherPct: 0,        //其它成绩 - 默认0
        teachState: 0,      //默认状态为待确认
        academyId:'',       //此项不会提交
      },
      rules:{
        teachName: [
          { required: true, message: '请输入课程安排名称', trigger: 'blur' },
          { min: 2, max: 60, message: '请输入2 - 60个字符!', trigger: 'blur' }
        ],
        courseId: [
          { required: true, message: '请选择课程', trigger: 'blur' },
        ],
        teacherId: [
          { required: true, message: '请选择教师', trigger: 'blur' },
        ],
      }
    }
  },
  created() {
    this.termInit();
    this.academyInit();
    this.courseInit();
    let teachId = this.$route.params.teachId;
    if(teachId != null && parseInt(teachId) > 0){//如果有teachId则为修改，需要对数据进行初始化
      this.ruleForm.teachId = teachId;
      this.form.teachId = teachId;
      let path = 'http://localhost:8081/teach/getTeachTasks/1';
      this.$ajax.post(path,this.form).then(res=>{
        let result = res.data.list[0];
        if(res.data.list.length === 1 && parseInt(result.teachState) === 0){
          this.ruleForm = result;
          this.teacherInit(this.ruleForm.academyId,this.ruleForm.teacherId);
          this.ruleForm.student = [];
          for(let i = 0;result.students != null && i < result.students.length;i++){
            this.ruleForm.student.push(result.students[i].stuId);
            this.studentList.push(result.students[i]);
          }
          this.ruleForm.clazz = [];
          for(let i = 0;result.clazzes != null && i < result.clazzes.length;i++){
            this.ruleForm.clazz.push(result.clazzes[i].clazzId);
            this.clazzList.push(result.clazzes[i]);
          }
        }
        else{
          alert("课程安排不存在或没有修改权限!");
          this.$router.push('/admin/teachTaskMGMT');
        }
      })
    }
  },
  methods:{
    submitForm(formName){//提交
      this.$refs[formName].validate((valid) => {//校验格式
        if (valid && this.check()) {//校验通过
          let path = 'http://localhost:8081/teach/updateTeachTask';
          this.$ajax.post(path,this.ruleForm).then(res=>{
            if(res.data.status === 0){
              this.$message.success(res.data.message);
              this.$router.push('/admin/teachTaskMGMT');
            }
            else{
              if(this.ruleForm.teachId === -1)
                this.$message.error('添加失败!');
              else
                this.$message.error(res.data.message);
            }
          })
        }
      });
    },
    check(){//输入校验
      let ruleForm = this.ruleForm;
      let result = true;
      if(parseInt(ruleForm.fullScore) > 9999){
        result = false;
        this.$message.error('您输入的满分成绩太大了!');
      }
      if(parseInt(ruleForm.passingScore) > parseInt(ruleForm.fullScore)){
        result = false;
        this.$message.error('及格成绩不能超过满分成绩!');
      }
      if(ruleForm.usualPct === '') ruleForm.usualPct = 0;
      if(ruleForm.expPct === '') ruleForm.expPct = 0;
      if(ruleForm.midPct === '') ruleForm.midPct = 0;
      if(ruleForm.finalPct === '') ruleForm.finalPct = 0;
      if(ruleForm.otherPct === '') ruleForm.otherPct = 0;
      let pct = parseInt(ruleForm.usualPct + '') + parseInt(ruleForm.expPct + '')
          + parseInt(ruleForm.midPct + '') + parseInt(ruleForm.finalPct + '')
          + parseInt(ruleForm.otherPct + '');
      if(pct !== 100){
        result = false;
        this.$message.error('成绩组成百分比之和应当等于100!');
      }
      if(ruleForm.clazz.length === 0 && ruleForm.student.length === 0){
        result = false;
        this.$message.error('请至少选中一个班级或学生!');
      }
      else{//清除不必要的学生选项(该学生已在班级中被选中)
        let ruleForm_clazz = ruleForm.clazz;
        let ruleForm_student = ruleForm.student;
        let studentList = this.studentList;
        let check;
        let count = 0;
        for(let i = 0;i < ruleForm_student.length;){
          check = false;//默认不清除
          for(let j = 0;j < studentList.length;j++){
            for(let k = 0;k < ruleForm_clazz.length;k++){
              if(ruleForm_student[i] === studentList[j].stuId
                  && studentList[j].clazzId === ruleForm_clazz[k]){
                check = true;//被选中的学生已包含在被选中的班级中则需要清除
              }
            }
          }
          if(check){
            ruleForm_student.splice(i,1);
            count++;
          }
          else        i++;
        }
        if(count > 0) this.$message.success('已为您自动清除了不必要的学生选项!');//有学生被清除
      }
      return result;
    },
    findStudent(){//查找学生
      let ruleForm_student = this.ruleForm.student;
      let studentList = this.studentList;
      let check;
      for(let i = 0;i < studentList.length;){//清空未被选中的学生选项
        check = true;//默认清除数据
        for(let j = 0;j < ruleForm_student.length;j++){
          if(studentList[i].stuId === ruleForm_student[j]){
            check = false;//重复的数据保留
            break;
          }
        }
        if(check)   studentList.splice(i,1);
        else        i++;
      }
      let path;
      if(this.studentId === '')
        path = `http://localhost:8081/student/findStudent/0`;
      else
        path = `http://localhost:8081/student/findStudent/${this.studentId}`;
      this.$ajax.post(path).then(res=>{
        if(res.data.status === 0){
          let list = res.data.list;
          for(let i = 0;i < list.length;){//清空查找结果中已存在的学生选项
            check = false;//默认保留数据
            for(let j = 0;j < studentList.length;j++){
              if(list[i].stuId === studentList[j].stuId){
                check = true;//重复的数据清除
                break;
              }
            }
            if(check)   list.splice(i,1);
            else        i++;
          }
          if(list.length > 0){
            list.forEach(function(item){//将不重复的数据追加
              studentList.push(item);
            })
          }
          else{//没有可以追加的数据
            this.$message('本次查找未找到新的可供选择的学生!');
          }
        }
        else{
          this.$message.error(res.data.message);
        }
      })
    },
    findClazz(){//查找班级
      let ruleForm_clazz = this.ruleForm.clazz;
      let clazzList = this.clazzList;
      let check;
      for(let i = 0;i < clazzList.length;){//清空未被选中的班级选项
        check = true;//默认清除数据
        for(let j = 0;j < ruleForm_clazz.length;j++){
          if(clazzList[i].clazzId === ruleForm_clazz[j]){
            check = false;//重复的数据保留
            break;
          }
        }
        if(check)   clazzList.splice(i,1);
        else        i++;
      }
      let path;
      if(this.clazzId === '')
        path = `http://localhost:8081/clazz/findClazz/0`;
      else
        path = `http://localhost:8081/clazz/findClazz/${this.clazzId}`;
      this.$ajax.post(path).then(res=>{
        if(res.data.status === 0){
          let list = res.data.list;
          for(let i = 0;i < list.length;){//清空查找结果中已存在的班级选项
            check = false;//默认保留数据
            for(let j = 0;j < clazzList.length;j++){
              if(list[i].clazzId === clazzList[j].clazzId){
                check = true;//重复的数据清除
                break;
              }
            }
            if(check)   list.splice(i,1);
            else        i++;
          }
          if(list.length > 0){
            list.forEach(function(item){//将不重复的数据追加
              clazzList.push(item);
            })
          }
          else{//没有可以追加的数据
            this.$message('本次查找未找到新的可供选择的班级!');
          }
        }
        else{
          this.$message.error(res.data.message);
        }
      })
    },
    teacherInit(val,initId){//根据学院初始化教师
      this.ruleForm.teacherId = '';
      if(val !== ''){
        let path = `http://localhost:8081/teacher/getTeachers/${val}`;
        this.$ajax.post(path).then(res=>{
          this.teacher = res.data.list
          if(initId !== '')
            this.ruleForm.teacherId = initId;
        })
      }
      else{
        this.teacher = null;
      }
    },
    courseInit(){//初始化课程
      let path = 'http://localhost:8081/course/getCourses';
      this.$ajax.post(path).then(res=>{
        this.course = res.data.list
      })
    },
    academyInit(){//初始化学院
      let path = 'http://localhost:8081/academy/selectAcademyCanUse';
      this.$ajax.post(path).then(res=>{
        this.academy = res.data.list
      })
    },
    termInit(){//初始化学期
      let path = 'http://localhost:8081/term/getTerms';
      this.$ajax.post(path).then(res=>{
        this.terms = res.data.list
        this.ruleForm.termId=this.terms[0].termId;
      })
    },
    returnPage(){//返回
      this.$confirm('您真的要放弃所有未保存的内容，并立即返回吗?').then(()=>{
        this.$router.push('/admin/teachTaskMGMT');
      })
    }
  }
}
</script>

<style scoped>

</style>